package vn.com.epi.re.tools;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;

import org.apache.hadoop.conf.Configuration;

import com.google.common.io.Resources;

public final class ConfigurationUtils {
    
    private ConfigurationUtils() { }

	public static Configuration loadConfigurationFromClasspath() throws IOException {
		Configuration conf = new Configuration();
        URL coreSiteUrl = getResource("core-site.xml");
		if (coreSiteUrl == null) {
			throw new IOException("Please put Hadoop conf dir into classpath");
		}
		conf.addResource(coreSiteUrl);
		URL hdfsSiteUrl = getResource("hdfs-site.xml");
		if (hdfsSiteUrl != null) {
            conf.addResource(hdfsSiteUrl);
        }
		URL mapReduceSiteUrl = getResource("mapred-site.xml");
		if (mapReduceSiteUrl != null) {
            conf.addResource(mapReduceSiteUrl);
        }
		return conf;
	}
	
	private static URL getResource(String path) {
	    return ConfigurationUtils.class.getClassLoader().getResource(path);
	}

	public static String findConfDirInClassPath() throws IOException {
		URL coreSiteUrl = Resources.getResource("core-site.xml");
		if (coreSiteUrl == null) {
			return null;
		}
		File coreSiteFile = new File(
				URLDecoder.decode(coreSiteUrl.getFile(), "UTF-8"));
		return coreSiteFile.getParent();
	}

}
